<?php

function unique_id(){
	$crc = dechex(crc32(microtime(true))) . mt_rand(1, 10000);
	return $crc;
}


function json($file){
	return json_decode(file_get_contents($file), true);
}

define('DIR', unique_id());
mkdir(DIR, 0755, true);

$manifest = json('manifest.json');

$map = [
	'resource/default.res.json' => DIR .'/'. unique_id() .'.json'
];

foreach(['initial', 'game'] as $key){
	foreach($manifest[$key] as $k => $file){
		$map[$file] = DIR .'/'. unique_id();
		rename($file, $map[$file]);
		$content = str_replace(
			['resource/default.res.json', '"resource/"'],
			[$map['resource/default.res.json'], '"'. DIR .'"'],
			file_get_contents($map[$file])
		);

		file_put_contents($map[$file], $content);

		$manifest[$key][$k] = $map[$file];
	}
}
file_put_contents('manifest.json', json_encode($manifest));


$res = json('resource/default.res.json');
foreach($res['resources'] as $k => $r){
	$map[$r['url']] = unique_id();
	if($r['type'] == 'sheet'){
		$map[$r['url']] .= '.json';
		$png = 'resource/'. str_replace('.json', '.png', $r['url']);
		rename($png, DIR .'/'. basename($png));
	}else if($r['type'] == 'json'){
		$map[$r['url']] .= '.json';
	}

	rename('resource/'. $r['url'], DIR .'/'. $map[$r['url']]);
	
	$res['resources'][$k]['url'] = $map[$r['url']];
}

echo $map['resource/default.res.json'], "\n";
file_put_contents($map['resource/default.res.json'], json_encode($res));